package lc.q101_150;

import java.util.HashMap;
import java.util.Map;

public class Q138 {
    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        // 难点是random,第一种通过hash来记录映射关系
        // 第二种方式，复制节点并插入到下一节点位置，变成了双链，然后就得到random位置了
        Node virNode = new Node(0);
        Node cur = virNode;
        Map<Node, Node> mapping = new HashMap<>();
        Node oh = head;
        while (head != null) {
            cur.next = new Node(head.val);
            cur = cur.next;
            mapping.put(head, cur);
            head = head.next;
        }
        cur = virNode;
        while (cur.next != null && oh != null) {
            Node random = oh.random;
            if (random != null) {
                cur.next.random = mapping.get(random);
            }
            oh = oh.next;
            cur = cur.next;
        }
        return virNode.next;
    }
}
